package udpserver;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TrafficMeter extends JPanel implements Runnable {
    int width, height;
    int lastOut, lastIn;
    double actualOut, actualIn;
    Server server;
    ArrayList<Double> trafficIn, trafficOut;

    public TrafficMeter(Server server) {
        this.server = server;
        trafficIn = new ArrayList<Double>();
        trafficOut = new ArrayList<Double>();
        width = 500;
        height = 240;
        this.setPreferredSize(new Dimension(width, height));
        this.repaint();
    }

    @Override
    public void paintComponent(Graphics g) {
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, width, height);

        int sizeOut = trafficOut.size();
        int sizeIn = trafficIn.size();

        //mrizka
        g.setColor(Color.DARK_GRAY);
        for (int i = 0; i < 15; i++) {
            g.drawLine(0, i*20 + 10, width, i*20 + 10);
        }

        g.setColor(Color.RED);
        g.drawChars("out..5 kB/s".toCharArray(), 0, 11, 10, 10);
        for (int i = 0; i < sizeOut; i++) {
            g.drawLine(i, 110, i, 110 - (int)(trafficOut.get(sizeOut - i - 1)/50));
        }

        g.setColor(Color.GREEN);
        g.drawChars("in..5 kB/s".toCharArray(), 0, 10, 10, 130);
        for (int i = 0; i < sizeIn; i++) {
            g.drawLine(i, 230, i, 230 - (int)(trafficIn.get(sizeIn - i - 1)/50));
        }

    }

    @Override
    public void run() {
        while (true) {
            lastOut = server.trafficOutTotal;
            lastIn = server.trafficInTotal;
            try {
                Thread.sleep(100);
            } catch (Exception e) {
            }
            actualOut = (server.trafficOutTotal - lastOut)*10;
            actualIn = (server.trafficInTotal - lastIn)*10;
            trafficOut.add(new Double(actualOut));
            trafficIn.add(new Double(actualIn));
            if (trafficOut.size() > width) trafficOut.remove(0);
            if (trafficIn.size() > width) trafficIn.remove(0);
            //System.out.println("trafficInTotal [B] " + server.trafficOutTotal + " actual traffic in [B/s] " + actualOut);
            //System.out.println("trafficInTotal [B] " + server.trafficInTotal + " actual traffic in [B/s] " + actualIn);
            this.repaint();
        }
    }
}
